package com.ruoyi.web.controller.wind;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ExecUtil;

import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.CommonUtil;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.common.utils.biz.ResultSaveModule;

import com.ruoyi.web.vo.WindGridDrawVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * <p>
 *  指定格网数据展示
 * </p>
 *
 * @author liuhl
 * @since 2024-07-03
 */
@RestController
@RequestMapping("/grid")
@AllArgsConstructor
@Slf4j
@Api(tags = "指定格网数据展示")
public class WindGridController {


    @PostMapping("/draw")
    @ApiOperation(value = "指定格网数据展示-绘制", notes = "根据页面入参计算出结果文件", httpMethod = "POST")
    public AjaxResult gridDraw(@RequestBody WindGridDrawVo vo) {

        String tmpDir = PathUtil.tmpModuleDir(BizModule.COLLECT);

        String originDir = PathUtil.outputDir() +
                PathUtil.moduleDirs().getCollect().get("dir") +
                PathUtil.moduleDirs().getCollect().get("result");

        String type = vo.getType();
        List<String> command = null;
        if ("satellite".equals(type)){
            String codePath = PathUtil.codeModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("grid_satellite_plot");

            String resultType = vo.getResultType();
            String level = ("horizon".equals(resultType) || "trajectory".equals(resultType))?vo.getLevel():"all";
            String area = CommonUtil.getArea(vo.getLongitudeRange(), vo.getLatitudeRange());
            String dataType = StrUtil.isBlank(vo.getDataType())? "None" : vo.getDataType();
            String dataTime = StrUtil.isBlank(vo.getEndTime())? vo.getStartTime() : vo.getStartTime() + "-" + vo.getEndTime();
            String resultResolution = "[" + vo.getResultResolution() + "]";
            //Plot_Picture(filepath_obs, fileout, calculate_type, element_type, data_name, data_type, area, level,
            //                          data_time, ratio, inter_method, result_type, element)

            command = Stream.of("python",
                    "-u",
                    codePath,
                    originDir,
                    tmpDir,
                    vo.getCalculateType(),
                    vo.getElementType(),
                    vo.getDataName(),
                    dataType,
                    area,
                    level,
                    dataTime,
                    resultResolution,
                    vo.getInsertMethod(),
                    vo.getResultType(),
                    vo.getElements()
            ).collect(Collectors.toList());
        }

        if ("radar".equals(type)){

            String codePath = PathUtil.codeModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("grid_radar_plot");
            String calculateType = vo.getCalculateType();
            String hours = "00-00";
            String dataTime = "";
            String startTime = vo.getStartTime();
            String endTime = vo.getEndTime();
            if ("hourly".equals(calculateType)){
                String[] startSplit = startTime.split("-");
                String[] endSplit = endTime.split("-");
                dataTime = startSplit[0] + "-" + endSplit[0];
                hours = startSplit[1] + "-" + endSplit[1];
            } else {
                dataTime = startTime + "-" + endTime;
            }

            //Plot_Radar_Picture(filepath_obs, fileout, time_type, data_time, hours, data_name, element, ratio)
            command = Stream.of("python",
                    "-u",
                    codePath,
                    originDir,
                    tmpDir,
                    calculateType,
                    dataTime,
                    hours,
                    vo.getDataName(),
                    vo.getElements(),
                    vo.getResultResolution()
            ).collect(Collectors.toList());
        }

        String commandStr = command.stream().collect(Collectors.joining(" "));

        String results = ExecUtil.execCmdWithResult(commandStr);
        if (results == null || !results.contains("###")){
            return AjaxResult.error(results);
        }
        String[] split = results.split("###");
        String jsonData = split[1];

        Map<String,Object> resultMap = new LinkedHashMap<>();
        resultMap.put("jsonData",jsonData);

        Map<String,Object> dataMap = JSONUtil.toBean(jsonData,Map.class);
        String filePath = dataMap.get("picture_name").toString();

        resultMap.put("resultData", JSONUtil.toJsonStr(CollectionUtil.newArrayList(filePath)));
        resultMap.put("module", ResultSaveModule.MODEL_REVISE);
        resultMap.put("submodule", ResultSaveModule.MODEL_REVISE_GRID);

        return AjaxResult.success(resultMap);

    }

}
